
package com.oa.office.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.oa.office.biz.ReportTableBiz;
import com.oa.office.entity.ReportTableWithBLOBs;
import com.oa.office.util.UtilHelp;

@Controller
@RequestMapping("/img")
public class ImgController {
	@Resource
	private UtilHelp path;
	@Resource
	private ReportTableBiz reportTableBiz;
	
	@RequestMapping("upload")
	public void upload(MultipartHttpServletRequest request, PrintWriter out){
		try {
			MultipartFile file = request.getFile("upload");
			String fileName = UUID.randomUUID().toString();
			File file1 = new File(path.getPath());
			if(!file1.exists()){
				file1.mkdirs();
			}
			File newFile = new File(path.getPath() + fileName);
			file.transferTo(newFile);
			String callback = request.getParameter("CKEditorFuncNum");   
	        out.println("<script type=\"text/javascript\">");  
	        out.println("window.parent.CKEDITOR.tools.callFunction("+ callback + ",'" + 
	        		request.getContextPath() + "/img/show/"+ fileName + "','')");   
	        out.println("</script>"); 
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/show/{name}")
	public void show(@PathVariable("name") String name,HttpServletResponse response){
		File file = new File(path.getPath()+name);
		if(file.exists()){
			try {
				FileInputStream fis = new FileInputStream(file);
				ServletOutputStream sos=response.getOutputStream();
				byte [] b  = new byte[1024];
				int len=0;
				while ((len=fis.read(b))!=-1) {
					sos.write(b, 0, len);
				}
			fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	@RequestMapping("/download/{name}")
	public void download(@PathVariable("name") String name,HttpServletResponse response){
		String filename="1.jpg";
		String spar="%"+name+"%";
		ReportTableWithBLOBs rtwb=reportTableBiz.selectReportTableLikeSpar(spar);
		String[] spars=rtwb.getSpar().split(",");
		for(String str:spars){
				if(str.indexOf(name)>=0){
					filename=str.replace(name, "");
				}
		}
		response.setHeader("Content-Disposition", "attachment;filename="+filename);
		show(name, response);
	}
}
